package com.ifudata.dvp.app.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.ifudata.dvp.app.dao.factory.MapperFactory;
import com.ifudata.dvp.app.dao.mapper.base.bo.AppMenu;
import com.ifudata.dvp.base.exception.BusinessException;
import com.ifudata.dvp.sdk.constant.ExceptionCodeConstant;
import com.ifudata.dvp.sdk.util.StringUtil;

/**
 * 
 * @description
 * @author yuhuan 2018年10月26日
 * @Modifier
 */
public class GetDataUtil {

	// 先放这 以后通用了 就提出去
	public static List<List<String>> getDataBySqlKey(AppMenu menu){
		return getDataBySqlKey(menu, null);
	}

	public static List<List<String>> getDataBySqlKey(AppMenu menu, Map<String, String> param) {

		LinkedList<List<String>> result = new LinkedList<List<String>>();
		if( menu!=null ){
			String sql = menu.getConfigSql();
			if (!StringUtil.isBlank(sql)) {
				if ( param!=null ) {
					for (String key : param.keySet()) {
						sql = sql.replace(key, param.get(key));
					}
				}
				
				// 判断是否<<transform>>
				boolean transform = false;
				if( sql.trim().startsWith("<<transform>>") ){
					transform = true;
					sql = sql.replace("<<transform>>", "");
				}
				
				List<Map<String, Object>> list = MapperFactory.getSimpleDataMapper().query(sql);
				
				// 需要行列转换
				if( transform ){
					for(int i=0; i<menu.getConfigColumn(); i++){
						result.add(new ArrayList<String>());
					}
					
					for (Map<String, Object> map : list) {
						for (int i = 1; i <= menu.getConfigColumn(); i++) {
							Object v = map.get(String.valueOf(i));
							if (v != null) {
								result.get(i-1).add(v.toString());
							} else {
								result.get(i-1).add("-");
							}
						}
					}
				}else{
					for (Map<String, Object> map : list) {
						List<String> resultColumn = new ArrayList<String>();
						// 根据columnCnt 依次取出结果
						for (int i = 1; i <= menu.getConfigColumn(); i++) {
							Object v = map.get(String.valueOf(i));
							if (v != null) {
								resultColumn.add(v.toString());
							} else {
								resultColumn.add("-");
							}
						}
						result.add(resultColumn);
					}
				}
			}
			
			// 补充标题
			if( StringUtil.isBlank(menu.getConfigTitle())==false ){
				String line[] = menu.getConfigTitle()
						.replaceAll("\r", "")
						.replace(System.getProperty("line.separator"), "")
						.split("<br>");
				for( int i=line.length-1; i>=0; i-- ){
					if( StringUtil.isBlank(line[i]) ) continue;
					String[] ts = line[i].trim().split(",");
					result.addFirst(Arrays.asList(ts));
				}
			}
					
			return result;
		} else {
			throw new BusinessException(ExceptionCodeConstant.NO_RESULT);
		}
	}
}
